<template>
    <div class="wrapper">
        <!-- 报表标题组件-->
        <ReportTitle :titleInfo="titleInfo" :isExport="false" :isAdd="false" />
        <div class="userMain">
            <div class="left main-item">
                <span class="title">基础信息</span>
                <ReportSearch :loading="loading" :searchFormDatas="searchFormDatas" v-model:searchForm="searchForm"
                    :isBtnShow="false" ref="searchRef" />
            </div>
            <div class="right main-item">
                <span class="title">角色权限</span>
                <div class="tabs">
                    <el-radio-group v-model="curTab">
                        <div v-for="tabKey in Object.keys(tabDatas)" :key="tabKey" class="tab-item" :class="{ 'activeTab': tabKey === curTab }" @click="changeTab(tabKey)">
                            <el-radio :value="tabKey" size="large">{{ tabDatas[tabKey]['label']}}</el-radio>
                        </div>
                    </el-radio-group>
                </div>
                <div class="roleBox">
                    <el-scrollbar style="height:calc(100vh - 310px)">
                        <el-tree ref="treeRef" :data="treeData" class="eq-tree" show-checkbox node-key="nodeId" :props="defaultProps" :default-expanded-keys="defaultExpandKeys"></el-tree>
                    </el-scrollbar>
                </div>
            </div>
        </div>
        <div class="userFooter">
            <span class="searchBtn" @click="handleSave">保存</span>
            <span class="resetBtn" @click="handleCancel">取消</span>
        </div>
        
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

import ReportTitle from '@/components/reportTitle/index.vue';
import ReportSearch from '@/components/reportSearch/index.vue';

import * as server from '@/api/modules/systemManage';
import { apiFn } from '@/utils/utilFns';

const emit = defineEmits(['updateRoleInfo']);

const props = defineProps({
    roleInfo: {
        type: Object,
        default: {}
    }
}); 

const defaultProps = {
    children: 'childrenList',
    label: 'text'
};

// 报表标题信息
const titleInfo = reactive({
    title: '角色新增',
    description: ""
});

// 当前标签页
const curTab = ref('dataPlatform');
const curSource = ref('1');

const treeRef = ref(null);
const searchRef = ref(null);
const treeData = ref([]);
const defaultExpandKeys = ref([]);
const roleData = ref({});

// 默认表单数据
const searchForm = reactive({
    roleName: '',
    remark: ''
});

const tabDatas = reactive({
    'dataPlatform': {
        label: '数据管理平台',
        source: '1',
        datas: []
    },
    'maintenancePlatform': {
        label: '智慧机务平台',
        source: '9',
        datas: []
    },
    'dataCloseloop': {
        label: '数据闭环平台',
        source: '10',
        datas: []
    }
});

// 检索条件数据
const searchFormDatas = ref([
    {
        id: 0,
        type: 'input',
        prop: 'roleName',
        label: '角色名称',
        api: () => { },
        placeholder: '请输入用户名',
        rules: [{ required: true, message: '角色名称不能为空', trigger: ['blur, change'] }]
    }, {
        id: 1,
        type: 'inputArea',
        prop: 'remark',
        label: '备注信息',
        api: () => { }
    }
]);

onMounted(() => {
    getRolePromission();
    getPromissionList();
});

const handleSave = () => {
    const formEl = searchRef.value.formRef;
    if (!formEl) return;
    
    const checkedKeys = treeRef.value.getCheckedKeys();

    if (!checkedKeys.length) {
        ElMessage.warning('请选择角色权限后提交!');
        return;
    }

    formEl.validate((valid) => {
        if (valid) {
            saveAddedRole(checkedKeys);
        } else {
            return false
        }
    })
};

// 添加角色
const saveAddedRole = (checkedKeys) => {
    const { roleName, remark } = searchForm;
    const params = {
        roleName,
        remark,
        permissionIds: checkedKeys.join(','),
        roleSource: curSource.value
    };

    apiFn(server.addRole, params)
        .then((res) => {
            const { code } = res;
            if (code === '200') {
                ElMessage.success('添加成功!');
                emit('updateRoleInfo', { type: 'list', roleInfo: {} });
            }
        }).catch(() => {
            ElMessage.error('添加失败!');
        });
};

const handleCancel = () => {
    emit('updateRoleInfo', { type: 'list', roleInfo: {} });
};

const changeTab = (key) => {
    curTab.value = key;
    curSource.value = tabDatas[key].source;
    getPromissionList();
};

const roleChange = (val) => {
    if (val.length === 0) {
        tabDatas[curTab.value]['datas'].forEach(item => item.disabled = false);
    } else {
        tabDatas[curTab.value]['datas'].forEach(item => {
            if (item.id === val[0]) {
                item.disabled = false
            } else {
                item.disabled = true;
            }
        })
    }
};

// 获取权限列表
const getPromissionList = () => {
    const params = { source: curSource.value };

    apiFn(server.getPermissionTree, params)
        .then((res) => {
            const { data = [] } = res;
            treeData.value = data
            defaultExpandKeys.value = data[0]?.nodeId;
        }).catch(() => {
            treeData.value = [];
        });
};

// 角色权限查询
const getRolePromission = () => {
    const { roleInfo } = props;
    const params = { roleId: roleInfo.roleId };

    apiFn(server.getPermissionTree, params)
        .then((res) => {
            const { data = {} } = res;
            roleData.value = data;
        }).catch(() => {
            roleData.value = {};
        });
}

</script>